package com.demo.watchconnectkitdemo;

import android.app.Application;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.util.Log;

import com.openharmony.watch.engine.WatchConnectEngine;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class App extends Application {
    private static final String TAG = "test-kitDemo";
    private static final Map<String, WatchConnectEngine> kits = new HashMap<>();
    @Override
    public void onCreate() {
        super.onCreate();

        new Thread(new Runnable() {
            @Override
            public void run() {
                initWatchConnectKit();
            }
        }).start();
    }

    private void initWatchConnectKit() {
        PackageManager packageManager = getPackageManager();
        Intent intent = new Intent();
        intent.setAction("OH_WATCH_CONNECT_ACTION");
        List<ResolveInfo> services = packageManager.queryIntentServices(intent, 0);
        for (ResolveInfo server : services) {
            Log.i(TAG, "MainActivity test serviceInfo.package name:" + server.serviceInfo.packageName);
            WatchConnectEngine engine = new WatchConnectEngine();
            boolean ret = engine.init("appId-1001-2001", "authId-6001-8001", getApplicationContext(), server.serviceInfo.packageName);
            if (ret) {
                Log.i("test-kitDemo", "App -> WatchConnectEngine init packageName(" + server.serviceInfo.packageName + ") success.");
            } else {
                Log.e("test-kitDemo", "App -> WatchConnectEngine init packageName(" + server.serviceInfo.packageName + ") fail.");
            }

            kits.put(server.serviceInfo.packageName, engine);
        }
    }

    public static WatchConnectEngine getWatchConnectEngine(String packageName) {
        return kits.getOrDefault(packageName, null);
    }

    public static WatchConnectEngine getWatchConnectEngine() {
        for (Map.Entry<String, WatchConnectEngine> entry : kits.entrySet()) {
            return entry.getValue();
        }
        return null;
    }

    public static int getWatchConnectEngineCount() {
        return kits.size();
    }
}
